import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  TextField,
  Button,
  List,
  ListItem,
  ListItemText,
  Alert,
} from '@mui/material';
import axios from 'axios';
import { API_BASE_URL } from '../config';
function Nodes() {
  // 钱包相关
  const [wallets, setWallets] = useState([]);
  const [walletsLoading, setWalletsLoading] = useState(true);
  const [walletsError, setWalletsError] = useState('');

  // 创建新用户相关状态
  const [newUser, setNewUser] = useState('');
  const [initialBalance, setInitialBalance] = useState('');
  const [userStatus, setUserStatus] = useState({ type: '', message: '' });

  useEffect(() => {
    fetchWallets();
  }, []);

  const fetchWallets = async () => {
    setWalletsLoading(true);
    setWalletsError('');
    try {
      const response = await axios.get(`${API_BASE_URL}/wallets`);
      // response.data: { address1: balance1, ... }
      const walletsArray = Object.entries(response.data).map(([address, balance]) => ({ address, balance }));
      setWallets(walletsArray);
      setWalletsLoading(false);
    } catch (err) {
      setWalletsError('获取用户列表失败：' + (err.response?.data || err.message));
      setWalletsLoading(false);
    }
  };

  // 创建新用户处理函数
  const handleCreateUser = async () => {
    setUserStatus({ type: '', message: '' });
    if (!newUser) {
      setUserStatus({ type: 'error', message: '请输入新用户名' });
      return;
    }
    if (initialBalance === '' || isNaN(Number(initialBalance)) || Number(initialBalance) < 0) {
      setUserStatus({ type: 'error', message: '请输入有效的初始余额' });
      return;
    }
    try {
      const response = await axios.post(`${API_BASE_URL}/wallets/new`, {
        address: newUser,
        initial_balance: Number(initialBalance),
      });
      setUserStatus({ type: 'success', message: response.data });
      setNewUser('');
      setInitialBalance('');
      fetchWallets(); // 创建成功后刷新用户列表
    } catch (error) {
      setUserStatus({ type: 'error', message: error.response?.data || '创建用户失败' });
    }
  };

  return (
    <Box>
      <Typography variant="h4" gutterBottom>
        用户管理
      </Typography>

      {/* 创建新用户区域 */}
      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Typography variant="h6" gutterBottom>创建新用户</Typography>
          {userStatus.message && (
            <Alert severity={userStatus.type} sx={{ mb: 2 }}>{userStatus.message}</Alert>
          )}
          <Box display="flex" gap={2} alignItems="center">
            <TextField
              label="用户名"
              value={newUser}
              onChange={e => setNewUser(e.target.value)}
              placeholder="请输入新用户名"
            />
            <TextField
              label="初始余额"
              type="number"
              value={initialBalance}
              onChange={e => setInitialBalance(e.target.value)}
              placeholder="请输入初始余额"
            />
            <Button variant="contained" color="primary" onClick={handleCreateUser}>
              创建用户
            </Button>
          </Box>
        </CardContent>
      </Card>

      {/* 已注册用户列表 */}
      <Card>
        <CardContent>
          <Typography variant="h6" gutterBottom>已注册用户</Typography>
          {walletsLoading ? (
            <Typography>正在加载用户列表...</Typography>
          ) : walletsError ? (
            <Alert severity="error">{walletsError}</Alert>
          ) : (
            <List>
              {wallets.map((wallet) => (
                <ListItem key={wallet.address}>
                  <ListItemText primary={wallet.address} secondary={`余额：${wallet.balance}`} />
                </ListItem>
              ))}
            </List>
          )}
        </CardContent>
      </Card>
    </Box>
  );
}

export default Nodes; 